package com.onec.service.thread.sync;

import java.util.concurrent.TimeUnit;

public class Sensor implements Runnable {

    private ParkingStatus parkingStatus;

    public Sensor(ParkingStatus parkingStatus) {
        this.parkingStatus = parkingStatus;
    }

    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {

            parkingStatus.carComeIn();
            parkingStatus.carComeIn();

            try {
                TimeUnit.MICROSECONDS.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            parkingStatus.motorComeIn();

            try {
                TimeUnit.MICROSECONDS.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            parkingStatus.motorGoOut();
            parkingStatus.carGoOut();

            parkingStatus.carGoOut();
        }
    }


    public static void main(String[] args) {
        ParkingCash parkingCash = new ParkingCash();
        ParkingStatus parkingStatus = new ParkingStatus(parkingCash);

        int numberSensor = Runtime.getRuntime().availableProcessors();

        Thread threads[] = new Thread[numberSensor];
        for (int i = 0; i < numberSensor; i++) {
            Sensor sensor = new Sensor(parkingStatus);
            Thread thread = new Thread(sensor);

            thread.start();

            threads[i] = thread;
        }


        for (int i = 0; i < numberSensor; i++) {
            try {
                threads[i].join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }

        System.out.println("---->" + parkingStatus.getNumberCar());
        System.out.println("---->" + parkingStatus.getNumberMotorCycles());
        parkingCash.close();
    }
}
